<?php
/**
 * Created by PhpStorm.
 * User: coolinmind
 * Date: 21/01/2019
 * Time: 16:23
 */

namespace App\Services\UCenter\UCenter;

use App\Models\Car\Car;
use App\Models\Car\CarDriver;
use App\Models\Company\Company;
use App\Models\UCenter\CompanyDriver;
use App\Models\User\User;
use App\Services\UCenter\WayBill;
use Illuminate\Support\Facades\DB;
use App\Services\Setting\SettingIndex;

class CompanyLogic
{
    public function companyAuthentication($data)
    {
        //判断用户是否提交过实名认证
        $checkRes = Company::where('user_id', $data['user_id'])->first();
        if ($checkRes) {
            return auto_failure($checkRes, '您已提交过企业认证');
        }
        $data['created_at'] = date('Y-m-d H:i:s');
        $data['updated_at'] = date('Y-m-d H:i:s');
        $res = Company::insert($data);
        return $res ?
            auto_success($res, '提交成功') :
            auto_failure($res, '提交失败');
    }

    //发送邀约
    public function sendInvite($data){
        $company = CompanyDriver::where('driver_id',$data['driver_id'])->where('status','<>',3)->first();
        if(!is_null($company)){
            return auto_failure($company,'此人已被邀约');
        }
        $data['created_at'] = date('Y-m-d H:i:s');
        $data['updated_at'] = date('Y-m-d H:i:s');
        $id = CompanyDriver::insertGetId($data);
        if($id){
            return auto_success($id,'邀约成功');
        }else{
            return auto_failure($id,'邀约失败');
        }
    }

    //邀约列表
    public function inviteList($data){
        if(!empty($data['company_id'])){
            $company = CompanyDriver::with('driver')->withCount('car')->where('status',$data['status'])->where('company_id',$data['company_id'])->get();
            if(!$company->isEmpty()){
               $company = $company->toArray();
            }
            foreach($company as $k=>$v){
                $company[$k]['driver']['enterprise_info'] = json_decode($v['driver']['enterprise_info']);
                $company[$k]['driver']['other_info'] = json_decode($v['driver']['other_info']);
            }
        }else{
            if($data['status'] == 4){
                $company = CompanyDriver::with('company','company_info')->where('driver_id', $data['driver_id'])->get();
            }else {
                $company = CompanyDriver::with('company','company_info')->where('status', $data['status'])->where('driver_id', $data['driver_id'])->get();
            }
            if(!$company->isEmpty()){
                $company = $company->toArray();
            }
            foreach($company as $k=>$v){
                $company[$k]['company']['enterprise_info'] = json_decode($v['company']['enterprise_info']);
                $company[$k]['company']['other_info'] = json_decode($v['company']['other_info']);
            }
        }
        return auto_success($company,'请求列表成功');
    }

    /**
     * 添加车辆
     * @param $data
     * @return array
     */
    public function addCars($data)
    {
        $data['created_at'] = date('Y-m-d H:i:s');
        $data['updated_at'] = date('Y-m-d H:i:s');
        DB::beginTransaction();
        try {
            //检测车牌号是否存在
            $checkRes = Car::where('number', $data['number'])->first();
            if($checkRes)
                return auto_failure(null, '该车牌号已存在');
            $res = Car::insert($data);
            User::where('id',$data['user_id'])->increment('car_count');
            DB::commit();
        } catch (\Exception $e) {
            auto_failure($e->getMessage(),'添加失败');
        }
        return $res ?
            auto_success($res, '添加成功') :
            auto_failure($res, '添加失败');
    }

    //司机与车辆进行绑定
    public function driverAndCar($data){
        $data['created_at'] = date('Y-m-d H:i:s');
        $data['updated_at'] = date('Y-m-d H:i:s');
        $car = CarDriver::where('driver_id',$data['driver_id'])->where('car_id',$data['car_id'])->where('status',1)->first();
        if(!is_null($car)){
            return auto_failure($car,"此车与该司机已绑定");
        }
        $res = CarDriver::insert($data);
        if($res){
            return auto_success($res,'绑定成功');
        }else{
            return auto_failure($res,'绑定失败');
        }
    }

    //移除司机与车辆进行绑定
    public function removeDriverAndCar($data){
        $res = CarDriver::where('id',$data['id'])->update(['status'=>2]);
        if($res){
            return auto_success($res,'移除成功');
        }
        return auto_failure($res,'移除失败');
    }

    //通过姓名或手机号查找公司下的员工
    public function companyDriverByRea($data){
        $name = $data['name'];
        $phone = $data['phone'];
        $driver = CompanyDriver::with('driver')->where('company_id',$data['company_id'])->where('status',2)->whereHas('driver',function($query) use ($name,$phone){
            if($name){
                $query->Where('name',$name);
            }
            if($phone) {
                $query->Where('phone', $phone);
            }
        })->get();
       if(!$driver->isEmpty()){
           return auto_success($driver,'获取成功');
       }else{
           return auto_failure($driver,'公司下没有该司机');
       }
    }

    //同意邀约
    public function agreeInvite($data){
        $res = CompanyDriver::where('id',$data['id'])->update(['status'=>2]);
        if($res){
            return auto_success($res,'同意成功');
        }
        return auto_failure($res,'同意失败');
    }

    //查看车辆下的司机
    public function carHasDriver($data){
        $res = CarDriver::with('driver')->where('car_id',$data['id'])->where('status',1)->get();
        if($res){
            return auto_success($res,'返回成功');
        }
        return auto_failure($res,'返回失败');
    }

    //车辆移除
    public function removeCompanyCar($data){
        $driver = CarDriver::where('car_id',$data['id'])->where('status',1)->get();
        if(!$driver->isEmpty()){
            return auto_failure($driver,'删除失败，车辆下有司机');
        }
        $car = Car::where('id',$data['id'])->first();
        if($car->is_busy == 1){
            return auto_failure($car,'该车辆占用中');
        }
        $res = Car::where('id',$data['id'])->update(['is_del'=>1]);
        User::where('id',$car->user_id)->decrement('car_count');
        if($res){
            return auto_success($res,'移除成功');
        }
        return auto_failure($res,'移除失败');
    }

    //车辆审核列表
    public function carCheckList($data){
        $check = Car::where('user_id',$data['user_id'])->where('is_del',0)->get();
        if($check->isEmpty()){
            return auto_failure($check,'无数据');
        }
        return auto_success($check,'返回成功');
    }

    //车辆管理
    public function driverManage($data){
        $query = CompanyDriver::with('driver')->withCount(['waybill'=>function($query){$query->whereIn('status',[1,2]);}])->where('company_id',$data['company_id'])->where('status',2);
        $name = $data['name'];
        $phone = $data['phone'];
        $card_type = explode(',',$data['card_type']);
        !empty($data['name']) && $query->whereHas('driver',function($query) use($name){$query->where('name',$name);});
        !empty($data['phone']) && $query->whereHas('driver',function($query) use($phone){$query->where('phone',$phone);});
        !empty($data['card_type']) && $query->whereHas('driver',function($query) use($card_type){$query->whereIn('card_type',$card_type);});
        !empty($data['count']) && $query->whereHas('driver',function($query){$query->where('car_count',0);});
        $car = $query->paginate(10);
        return auto_success($car,'返回成功');
    }

    //公司司机解绑
    public function companyDriverUnbind($data){
        $res = CompanyDriver::where('id',$data['id'])->first();
        $waybill = WayBill::where('driver_id',$res->driver_id)->whereIn('status',[1,2])->get();
        if(!$waybill->isEmpty()){
            return auto_failure($waybill,'司机正在运输中不能解绑');
        }
        $res->status = 4;
        $res->save();
        $carDriver = CarDriver::where('driver_id',$res->driver_id)->where('company_id',$res->company_id)->first();
        if(!is_null($carDriver)){
            $carDriver->status = 2;
            $carDriver->save();
        }
        if($res){
            return auto_success($res,'解绑成功');
        }
        return auto_failure($res,'解绑失败');
    }

    //拒绝邀约
    public function refuseInvite($data){
        $res = CompanyDriver::where('id',$data['id'])->update(['status'=>3]);
        if($res){
            return auto_success($res,'拒绝成功');
        }
        return auto_failure($res,'拒绝失败');
    }

    //运输管理
    public function wayBillManage($data){
        $_where = [
            'user_id' => $data['user_id'],
            'is_del' => 0
        ];
        $driver_id = $data['user_id'];
        if($data['type'] == 1) {
            $query = Car::where($_where)->where('is_busy', 0);
            !empty($data['number']) && $query->where('number',$data['number']);
            !empty($data['car_length']) && $query->where('car_length',$data['car_length']);
            !empty($data['weight']) && $query->where('weight',$data['weight']);
            !empty($data['plate_type']) && $query->where('plate_type',$data['plate_type']);
        }else if($data['type'] == 2){
            $query = Car::with('wayBill')->whereHas('wayBill',function($query) use($driver_id){$query->where('status',1); $query->where('ostatus',0);$query->where('driver_id',$driver_id);})->where($_where);
        }else{
            $query = Car::where($_where)->where('is_busy', 1);
        }
        $res = $query->paginate(8);
        return $res ?
            auto_success($res, '获取成功') :
            auto_failure($res, '获取失败');
    }

    //获取配置项
    public function getSetting($data){
        $res = SettingIndex::SettingCategory()->getSelection(['action' => $data['action']]);
        if($res){
            return auto_success($res,'返回成功');
        }
        return auto_failure($res,'返回失败');
    }

    //委托申请数量
    public function entrustCount($data){
        $count = CompanyDriver::where('status',1)->where('company_id',$data['user_id'])->count();
        return auto_success($count,'返回成功');
    }
}
